﻿using CommunityToolkit.Maui.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ZiChen.SoXunLeiPan.Common.Behaviors
{
    public class ButtonPressBehavior : Behavior<View>
    {
        // 正常状态背景色
        public Color NormalBackgroundColor { get; set; } = Colors.Transparent;

        // 按下状态背景色
        public Color PressedBackgroundColor { get; set; } = Color.FromHex("#F9F9F9");

        // 正常状态透明度
        public double NormalOpacity { get; set; } = 1.0;

        // 按下状态透明度
        public double PressedOpacity { get; set; } = 0.5;

        // 动画时长（毫秒）
        public uint AnimationDuration { get; set; } = 200;

        protected override void OnAttachedTo(View bindable)
        {
            base.OnAttachedTo(bindable);
            // 保存初始状态
            bindable.BackgroundColor = NormalBackgroundColor;
            bindable.Opacity = NormalOpacity;

            // 绑定事件

            bindable.Focused += OnReleased;
            bindable.Unfocused += OnReleased;
        }

        protected override void OnDetachingFrom(View bindable)
        {
            base.OnDetachingFrom(bindable);
            // 解绑事件
           
            bindable.Focused -= OnReleased;
            bindable.Unfocused -= OnReleased;
        }

        private async void OnPressed(object sender, System.EventArgs e)
        {
            if (sender is View view)
            {
                // 按下时的动画：同时改变背景色和透明度
                await Task.WhenAll(
                    view.BackgroundColorTo(PressedBackgroundColor, AnimationDuration),
                    view.FadeTo(PressedOpacity, AnimationDuration, Easing.SinOut)
                );
            }
        }

        private async void OnReleased(object sender, System.EventArgs e)
        {
            if (sender is View view)
            {
                // 释放时的动画：恢复到正常状态
                await Task.WhenAll(
                    view.BackgroundColorTo(NormalBackgroundColor, AnimationDuration),
                    view.FadeTo(NormalOpacity, AnimationDuration, Easing.SinIn)
                );
            }
        }
    }
}
